# -*- coding:utf-8 -*-

import pandas as pd

class TimeSeries(pd.DataFrame):
    """
    可以盛装一或多个TS数据.
    """
    def __init__(self, data=None, index=None, columns=None, dtype=None,
                 copy=False):
        """

        :param data:
        :param index:
        """
        super(TimeSeries, self).__init__(data=data, index=index, columns=columns, dtype=dtype,
                 copy=copy)

    def save_json(self, outfname, split_vars=True):
        """保存为风格兼容的JSON"""
        # result = {
        #     "uri": uri,
        #     "desc": desc,
        #     "tags": {"data": uri},
        #     "contents": {
        #         "data": {
        #             "info": {
        #                 "type": "timeseries",
        #                 "zh_varname": zh_varname_d.get(varname, varname),
        #                 "zh_dataset": u"全国9km再分析v2",
        #                 "zh_subset": u"时间序列",
        #                 "resolution": domain_resolution_d.get(domain),
        #                 "substitute_coords": {
        #                     "dataset": "zh_dataset",
        #                     "subset": "zh_subset",
        #                     "varname": "zh_varname",
        #                     "domain": "resolution"
        #                 },
        #             },
        #             "coords": {
        #                 "dataset": "china_9km_anl2",
        #                 "subset": "PT",
        #                 "domain": domain,
        #                 "varname": varname,
        #                 "time": year,
        #                 "level": level,
        #                 "jy_ix": jy_ix
        #             },
        #             "data": {
        #                 "begdt": begdt,
        #                 "interval": interval,
        #                 "values": values,
        #                 "units": units_dict[varname],
        #                 "min": value_min,
        #                 "max": value_max,
        #                 "invalid": value_invalid,
        #                 "suggest_range": pt_suggest_range_d[varname]
        #             }
        #         }
        #     }
        # }

    def save_csv(self, outf, spec=None):
        if spec.startswith('wrfop_'):  # 老的wrfop的时间序列数据格式
            if spec == 'wrfop_wind':
                header = 'datetime,wspd,wdir,td,pres,rh,rho,snow'
                fmt_str = '{datetime:%Y-%m-%d %H:%M:%S}{wspd:10.3}{wdir:10.3}{t:10.3}{p:12.3}{rh:10.3}{rhoair:10.3}{snow:10.3}\n'
            elif spec == 'wrfop_solar':
                header = 'datetime,wspd,wdir,swdown,glw,td2m,tsd,dpt2m,psfc,rh2m,qv2m,clflo,clfhi'
                fmt_str = '{datetime:%Y-%m-%d %H:%M:%S}{wspd:10.3}{wdir:10.3}{ghi:10.3}{glw:10.3}{t2m:10.3}{tskin:10.3}{tdew2m:10.3}{p:10.3}{rh2m:10.3}{q2m:10.3}{clflo:10.3}{clfhi:10.3}\n'

            close = False
            if isinstance(outf, (str, unicode)):
                outf = open(outf, 'w')
                close = True

            try:
                outf.write(header + '\n')
                for i, v in self.iterrows():
                    vd = v.to_dict()
                    vd['datetime'] = i
                    outf.write(fmt_str.format(vd))
            except Exception:
                raise
            finally:
                if close:
                    outf.close()
        else:
            self.to_csv(outf, na_rep='nan')

    def save_h5(self, outf, spec=None):
        self.to_hdf(outf, 'df', format='table')
